<template>
  <div class="cgl-container">
    <!-- 头部标题 -->
    <div class="header">
      <div class="titleMain">连退1630炉辊张力辊打滑预警模型</div>
    </div>

    <!-- Top Charts Area -->
    <div class="top-charts-panel">
      <div class="chart-card status-chart">
        <div class="chart-header">
          <div class="title-bar">
            <span class="blue-bar"></span>
            <span class="title-text">工艺辊服役状态</span>
          </div>
          <div class="chart-buttons">
            <el-radio-group v-model="barChartType" size="small" @change="updateBarChart">
              <el-radio-button label="超差辊"></el-radio-button>
              <el-radio-button label="公里数"></el-radio-button>
              <el-radio-button label="粗糙度"></el-radio-button>
            </el-radio-group>
          </div>
        </div>
        <div class="chart-content" ref="statusBarChartRef"></div>
      </div>
      <div class="chart-card line-chart">
        <div class="chart-header">
          <div class="title-bar">
            <span class="blue-bar"></span>
            <span class="title-text">出口段</span>
          </div>
          <div class="chart-controls">
            <el-select v-model="torqueSelect1" placeholder="选择关键辊" size="small" class="torque-select"
              @change="handleTorqueSelect1Change">
              <el-option v-for="option in torqueOptions1" :key="option.value" :label="option.label"
                :value="option.value">
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="chart-content" ref="lineChart1Ref"></div>
      </div>
      <div class="chart-card line-chart">
        <div class="chart-header">
          <div class="title-bar">
            <span class="blue-bar"></span>
            <span class="title-text">工艺段</span>
          </div>
          <div class="chart-controls">
            <el-select v-model="torqueSelect2" placeholder="选择关键辊" size="small" class="torque-select"
              @change="handleTorqueSelect2Change">
              <el-option v-for="option in torqueOptions2" :key="option.value" :label="option.label"
                :value="option.value">
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="chart-content" ref="lineChart2Ref"></div>
      </div>
      <div class="chart-card line-chart">
        <div class="chart-header">
          <div class="title-bar">
            <span class="blue-bar"></span>
            <span class="title-text">入口段</span>
          </div>
          <div class="chart-controls">
            <el-select v-model="torqueSelect3" placeholder="选择关键辊" size="small" class="torque-select"
              @change="handleTorqueSelect3Change">
              <el-option v-for="option in torqueOptions3" :key="option.value" :label="option.label"
                :value="option.value">
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="chart-content" ref="lineChart3Ref"></div>
      </div>
      <!-- <div class="chart-card line-chart">
        <div class="chart-header">
          <div class="title-bar">
            <span class="blue-bar"></span>
            <span class="title-text">活套底辊</span>
          </div>
          <div class="chart-controls">
            <el-select
              v-model="torqueSelect4"
              placeholder="关键辊转矩"
              size="small"
              class="torque-select"
            >
              <el-option label="关键辊转矩" value="1"></el-option>
            </el-select>
          </div>
        </div>
        <div class="chart-content" ref="lineChart4Ref"></div>
      </div> -->
    </div>

    <!-- Process Flow and Stats Area -->
    <el-row class="process-stats-panel">
      <!-- 辊位图 点击热区  -->
      <div class="roll-pos-image-block" @click="rollPosImageRef?.openDialog('3')"></div>
      <div class="roll-pos-image-block" @click="rollPosImageRef?.openDialog('2')"></div>
      <div class="roll-pos-image-block" @click="rollPosImageRef?.openDialog('1')"></div>
      <!-- 报警信息 - 左上角 -->
      <div class="warning-banner warning-banner-top-left">
        <i class="fa fa-exclamation-triangle"></i>
        报警信息 {{ warningMessage }}
      </div>

      <div class="svg">
        <svg-load :name="technologicalName" style="z-index:999"></svg-load>
      </div>

      <!-- 张力信息 - 右上角 -->
      <div class="tension-info tension-info-top-right">
        设定张力:
        <strong>{{ tensionInfo.set }}KN</strong> 实际张力:
        <strong>{{ tensionInfo.actual }}KN</strong>
      </div>

      <!-- Added Data Layer for Gauges and Live Data -->
      <div class="zlgdh-added-data-layer">
        <!-- Gauges -->
        <div class="gauge-wrapper zlgdh-gauge-exit">
          <div class="gauge-title">出口速度</div>
          <div id="zlgdh_speed_exit" class="gauge-container"></div>
        </div>
        <div class="gauge-wrapper zlgdh-gauge-process">
          <div class="gauge-title">工艺速度</div>
          <div id="zlgdh_speed_process" class="gauge-container"></div>
        </div>
        <div class="gauge-wrapper zlgdh-gauge-ent">
          <div class="gauge-title">入口速度</div>
          <div id="zlgdh_speed_ent" class="gauge-container"></div>
        </div>

        <!-- Live Data Boxes -->
        <div class="semitransp_box zlgdh_inlet_looper">
          <p>入口活套:</p>
          <p>{{ numberFormat1(zlgdhInletLooper / 100) }} %</p>
        </div>
        <div class="semitransp_box zlgdh_middle_looper">
          <p>中间活套:</p>
          <p>{{ numberFormat1(zlgdhMiddleLooper / 100) }} %</p>
        </div>
        <div class="semitransp_box zlgdh_export_looper">
          <p>出口活套:</p>
          <p>{{ numberFormat1(zlgdhExportLooper / 100) }} %</p>

        </div>
        <div class="semitransp_box zlgdh_cpc_width" :class="{ 'is_alarm': zlgdhCpcWidthAlarm }">
          <p>CPC4测宽值:</p>
          <p>{{ numberFormat1(zlgdhCpcWidth) }}mm</p>
        </div>
        <div class="semitransp_box zlgdh_inlet_looper_time">
          <p>入口套时间:</p>
          <p>{{ zlgdhInletLooperTime }}</p>
        </div>
        <div class="semitransp_box zlgdh_middle_looper_time">
          <p>中间套时间:</p>
          <p>{{ zlgdhMiddleLooperTime }}</p>
        </div>
        <div class="semitransp_box zlgdh_export_looper_time">
          <p>出口套时间:</p>
          <p>{{ zlgdhExportLooperTime }}</p>

        </div>
        <div class="semitransp_box zlgdh_uncoiler_len_a">

          <p>#1开卷机剩余长度:</p>
          <p>{{ numberFormat1(zlgdhUncoilerLenA) }} m</p>
        </div>
        <div class="semitransp_box zlgdh_uncoiler_len_b">
          <p>#2开卷机剩余长度:</p>
          <p>{{ numberFormat1(zlgdhUncoilerLenB) }} m</p>

        </div>
        <div class="semitransp_box zlgdh_coiler_len_a">
          <p>#1卷取长度:</p>
          <p>{{ numberFormat1(zlgdhCoilerLenA) }} m</p>
        </div>
        <div class="semitransp_box zlgdh_coiler_len_b">
          <p>#2卷取长度:</p>
          <p>{{ numberFormat1(zlgdhCoilerLenB) }} m</p>
        </div>
      </div>

      <!-- 酸轧厚度板形判别调优模型图 (替代SVG) -->
      <div class="process-diagram">
        <!-- 流程线条 -->
        <div class="process-flow-lines">
          <div class="flow-line horizontal-main"></div>
          <div class="flow-line vertical-line1"></div>
          <div class="flow-line vertical-line2"></div>
          <div class="flow-line vertical-line3"></div>
          <div class="flow-line vertical-line4"></div>
          <div class="flow-dot dot1"></div>
          <div class="flow-dot dot2"></div>
          <div class="flow-dot dot3"></div>
          <div class="flow-dot dot4"></div>
          <div class="flow-dot dot5"></div>
        </div>

        <!-- 数据流动效果 -->
        <div class="data-flow">
          <div class="data-particle particle1"></div>
          <div class="data-particle particle2"></div>
          <div class="data-particle particle3"></div>
          <div class="data-particle particle4"></div>
        </div>

        <!-- 统计卡片容器 -->
        <!--<div class="stats-overlay-container">
          <div class="stat-card stat1">
            <div class="stat-card-bg"></div>
            <div class="stat-card-content">
              <div class="stat-title">工艺段速度</div>
              <div class="stat-value">
                {{ productionStats.processSpeed }}
                <span class="unit">吨</span>
              </div>
              <div class="stat-icon">
                <i class="fa fa-chart-line"></i>
              </div>
            </div>
            <div class="stat-card-glow"></div>
          </div>

          <div class="stat-card stat2">
            <div class="stat-card-bg"></div>
            <div class="stat-card-content">
              <div class="stat-title">实际小时吨钢</div>
              <div class="stat-value">
                {{ productionStats.actualHourlyOutput }}
                <span class="unit">吨</span>
              </div>
              <div class="stat-icon">
                <i class="fa fa-cog fa-spin"></i>
              </div>
            </div>
            <div class="stat-card-glow"></div>
          </div>

          <div class="stat-card stat3">
            <div class="stat-card-bg"></div>
            <div class="stat-card-content">
              <div class="stat-title">小时吨钢</div>
              <div class="stat-value">
                {{ productionStats.hourlyOutput }}
                <span class="unit">吨</span>
              </div>
              <div class="stat-icon">
                <i class="fa fa-cog"></i>
              </div>
            </div>
            <div class="stat-card-glow"></div>
          </div>

          <div class="stat-card stat4">
            <div class="stat-card-bg"></div>
            <div class="stat-card-content">
              <div class="stat-title">日产量统计</div>
              <div class="stat-value">
                {{ productionStats.dailyOutput }}
                <span class="unit">吨</span>
              </div>
              <div class="stat-icon">
                <i class="fa fa-tachometer-alt"></i>
              </div>
            </div>
            <div class="stat-card-glow"></div>
          </div>
        </div>
-->
        <!-- 科技感装饰元素 -->
        <div class="tech-decorations">
          <div class="tech-circle circle1"></div>
          <div class="tech-circle circle2"></div>
          <div class="tech-hexagon hex1"></div>
          <div class="tech-hexagon hex2"></div>
          <div class="tech-scan-line"></div>
        </div>
      </div>
    </el-row>

    <!-- Warning Banner -->

    <!-- Bottom Table Area -->
    <div class="bottom-panel">
      <div class="tables-wrapper">
        <!-- Left Table Card -->
        <div class="table-card left-table-card">
          <div class="card-header">
            <div class="title-icon-left"></div>
            <span>报警时间与原因</span>
            <div class="title-icon-right"></div>
          </div>
          <el-table :data="tableData" class="left-table" style="width: 100%; height: 100%;" border size="small"
            :header-cell-style="rightTableHeaderStyle" :cell-style="rightTableCellStyle">
            <el-table-column prop="modifyTime" label="时间" />
            <el-table-column prop="rollID" label="打滑辊号" />
            <el-table-column prop="slipReason" label="打滑原因">
              <template #default="scope">
                <span>{{ scope.row.slipReason == 1 ? '周期打滑' : scope.row.slipReason == 2 ? '升降速打滑' : '瞬时打滑' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button v-if="!scope.row.confirmed" type="primary" size="small"
                  @click="confirmRow(scope.$index)">确认</el-button>
                <span v-else style="color: #67C23A;">已完成</span>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- Right Table Card -->
        <!-- <div class="table-card right-table-card">
          <div class="card-header">
            <div class="title-icon-left"></div>
            <span>详细信息</span>
            <div class="title-icon-right"></div>
          </div>
          <el-table
            :data="tableData"
            class="right-table"
            style="width: 100%; height: 100%;"
            border
            size="small"
            :header-cell-style="rightTableHeaderStyle"
            :cell-style="rightTableCellStyle"
          >
            <el-table-column prop="slipRollNo" label="打滑辊号" />
            <el-table-column prop="coilNo" label="卷号" width="70" />
            <el-table-column prop="steelGradeWidth" label="钢种宽" width="80" />
            <el-table-column prop="steelGradeThickness" label="钢种厚度" width="90" />
            <el-table-column prop="possibleSlipPos" label="可能打滑位" width="100" />
            <el-table-column prop="rollName" label="辊名" />
          </el-table>
        </div> -->
      </div>
    </div>
  </div>
  <RollPosImage r-group="5710/1630连退机组" :tab-list="rollPosImageList" ref="rollPosImageRef" />
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted, nextTick } from "vue";
import * as echarts from "echarts/core";
import { BarChart, LineChart, GaugeChart } from "echarts/charts";
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  MarkLineComponent
} from "echarts/components";
import { CanvasRenderer } from "echarts/renderers";
import axios from "axios";
import { ElMessage } from "element-plus";
import { rollingSimulationApi } from "/@/api/RollingSimulation/index";
import { refreshSVG, initialSVG, refreshGraphical } from "/@/common/refreshSVG";
import { weldMachineState } from "/@/views/common/FulllineTrack/full.line.track.status";
import { sleeveDeclineTime } from "/@/views/common/FulllineTrack/full.line.track.handle";
import { zlgdhApi } from "/@/api/zlgdh/index";
import { CAL1630TempCtrlApi } from "/@/api/CAL1630TempCtrl/index"
import RollPosImage from '/@/views/common/RollPosImage/RollPosImage.vue';
import { useUserStore } from '/@/store/modules/system/user';
// Register ECharts components
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  BarChart,
  LineChart,
  GaugeChart,
  CanvasRenderer,
  MarkLineComponent
]);

const rollPosImageList = [
  {
    label: 'CAL1630出口',
    key: '3',
    svgUrl: '/rollPosImage/1630/CAL1630出口.svg'
  },
  {
    label: 'CAL1630炉子',
    key: '2',
    svgUrl: '/rollPosImage/1630/CAL1630炉子.svg'
  },
  {
    label: 'CAL1630入口',
    key: '1',
    svgUrl: '/rollPosImage/1630/CAL1630入口.svg'
  }
]

const rollPosImageRef = ref<InstanceType<typeof RollPosImage> | null>(null);

// --- Refs for Charts ---
const statusBarChartRef = ref<HTMLElement | null>(null);
const lineChart1Ref = ref<HTMLElement | null>(null);
const lineChart2Ref = ref<HTMLElement | null>(null);
const lineChart3Ref = ref<HTMLElement | null>(null);
const lineChart4Ref = ref<HTMLElement | null>(null);

// --- ECharts Instances ---
let statusBarChartInstance: echarts.ECharts | null = null;
let lineChart1Instance: echarts.ECharts | null = null;
let lineChart2Instance: echarts.ECharts | null = null;
let lineChart3Instance: echarts.ECharts | null = null;
let lineChart4Instance: echarts.ECharts | null = null;
const exportLooper = ref<number>(0);

// --- 柱状图类型选择 ---
const barChartType = ref("超差辊");

// --- State ---
const torqueSelect1 = ref("");
const torqueSelect2 = ref("");
const torqueSelect3 = ref("");
const torqueSelect4 = ref("1");

// --- 下拉框选项 ---
const torqueOptions1 = ref<Array<{ label: string, value: string }>>([]); // 入口段
const torqueOptions2 = ref<Array<{ label: string, value: string }>>([]); // 工艺段
const torqueOptions3 = ref<Array<{ label: string, value: string }>>([]); // 出口段

// --- 实时数据轮询相关变量 ---
const realDataTimer1 = ref<NodeJS.Timeout | null>(null);
const realDataTimer2 = ref<NodeJS.Timeout | null>(null);
const realDataTimer3 = ref<NodeJS.Timeout | null>(null);

// --- 实时数据存储 ---
const realData1 = ref<Array<{ time: string, values: number[] }>>([]);
const realData2 = ref<Array<{ time: string, values: number[] }>>([]);
const realData3 = ref<Array<{ time: string, values: number[] }>>([]);

// --- 当前选中的dicPropCode值 ---
const currentDicPropCodes1 = ref<string[]>([]);
const currentDicPropCodes2 = ref<string[]>([]);
const currentDicPropCodes3 = ref<string[]>([]);

// --- 当前选中的dicPropName值 ---
const currentDicPropNames1 = ref<string[]>([]);
const currentDicPropNames2 = ref<string[]>([]);
const currentDicPropNames3 = ref<string[]>([]);

// --- 当前选中的dicPropType值（1:设定速度 2:实际速度 3:实际转矩 4:实际速度mpm） ---
const currentDicPropTypes1 = ref<number[]>([]);
const currentDicPropTypes2 = ref<number[]>([]);
const currentDicPropTypes3 = ref<number[]>([]);

const data = ref([
  { menuName: "ZLGDH1630s", menuTitle: '连退1630炉辊张力辊打滑模型主页', menuId: '1' }, {menuName: "slipHistory",menuTitle: '历史记录'},{ menuName: "slipReport", menuTitle: '打滑报表' }, { menuName: "tensionSelfLearning", menuTitle: '张力设定表' },{ menuName: "modelRuleSetting", menuTitle: '模型规则设定' }
]);



// --- Table Styles (Adopted from XGRPH.vue) ---
const rightTableHeaderStyle = {
  background: "#183272", // Darker blue for header
  color: "#b8e8ff",
  padding: "6px 0",
  textAlign: "center",
  fontWeight: "normal",
  borderBottom: "1px solid #06279d" // Use the border color from image
};

const rightTableCellStyle = {
  padding: "6px 0",
  textAlign: "center",
  color: "#c0c4cc",
  borderBottom: "1px solid #06279d",
  borderRight: "1px solid #06279d",
  fontSize: "12px"
  // Background will be handled by alternating row styles in CSS
};

// --- 生产统计信息 ---
const productionStats = reactive({
  dailyOutput: 1028.3,
  actualHourlyOutput: 152.5,
  hourlyOutput: 135.0,
  processSpeed: 210.7
});

// --- 张力信息 ---
const tensionInfo = reactive({
  set: 8.0,
  actual: 2.5
});

// --- 警告信息 ---
const warningMessage = ref("后卷过度异常, 模型进行了**调整");


interface TableRow {
  time: string;
  slipReason: string;
  slipRollNo: string;
  coilNo: number;
  steelGradeWidth: number;
  steelGradeThickness: number;
  possibleSlipPos: string;
  rollName: string;
  confirmed?: boolean;
}

// --- 表格数据 ---
const tableData = ref<TableRow[]>([
  {
    time: "2025-04-01 17: 32: 08",
    slipReason: "张力过度",
    slipRollNo: "Hooting1 Deflector R1",
    coilNo: 1,
    steelGradeWidth: 10,
    steelGradeThickness: 2,
    possibleSlipPos: "--",
    rollName: "Deflector R1",
    confirmed: false
  },
  {
    time: "2025-04-01 17: 32: 08",
    slipReason: "张力过度",
    slipRollNo: "Hooting1 Deflector R1",
    coilNo: 1,
    steelGradeWidth: 10,
    steelGradeThickness: 2,
    possibleSlipPos: "--",
    rollName: "Deflector R1",
    confirmed: false
  },
  {
    time: "2025-04-01 17: 32: 08",
    slipReason: "张力过度",
    slipRollNo: "Hooting1 Deflector R1",
    coilNo: 1,
    steelGradeWidth: 10,
    steelGradeThickness: 2,
    possibleSlipPos: "--",
    rollName: "Deflector R1",
    confirmed: false
  },
  {
    time: "2025-04-01 17: 32: 08",
    slipReason: "张力过度",
    slipRollNo: "Hooting1 Deflector R1",
    coilNo: 1,
    steelGradeWidth: 10,
    steelGradeThickness: 2,
    possibleSlipPos: "--",
    rollName: "Deflector R1",
    confirmed: false
  },
  {
    time: "2025-04-01 17: 32: 08",
    slipReason: "张力过度",
    slipRollNo: "Hooting1 Deflector R1",
    coilNo: 1,
    steelGradeWidth: 10,
    steelGradeThickness: 2,
    possibleSlipPos: "--",
    rollName: "Deflector R1",
    confirmed: false
  },
  {
    time: "2025-04-01 17: 32: 08",
    slipReason: "张力过度",
    slipRollNo: "Hooting1 Deflector R1",
    coilNo: 1,
    steelGradeWidth: 10,
    steelGradeThickness: 2,
    possibleSlipPos: "--",
    rollName: "Deflector R1",
    confirmed: false
  },
  {
    time: "2025-04-01 17: 32: 08",
    slipReason: "张力过度",
    slipRollNo: "Hooting1 Deflector R1",
    coilNo: 1,
    steelGradeWidth: 10,
    steelGradeThickness: 2,
    possibleSlipPos: "--",
    rollName: "Deflector R1",
    confirmed: false
  },
  {
    time: "2025-04-01 17: 32: 08",
    slipReason: "张力过度",
    slipRollNo: "Hooting1 Deflector R1",
    coilNo: 1,
    steelGradeWidth: 10,
    steelGradeThickness: 2,
    possibleSlipPos: "--",
    rollName: "Deflector R1",
    confirmed: false
  }
]);

// --- Pagination ---
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: tableData.value.length,
});

function confirmRow(index: number) {
  tableData.value[index].confirmed = true;
}

// --- 柱状图数据 ---
const barChartData = {
  超差辊: [35000, 45000, 30000, 45000, 25000, 40000, 35000, 30000],
  公里数: [10000, 30000, 15000, 25000, 20000, 10000, 15000, 20000],
  粗糙度: [15000, 5000, 10000, 5000, 25000, 15000, 10000, 15000]
};

// --- 标准值 ---
const standardValues = {
  超差辊: 32000,
  公里数: 18000,
  粗糙度: 12000
};

// --- 图表配置 ---
const baseBarOption = {
  tooltip: {
    trigger: "axis",
    axisPointer: { type: "shadow" },
    formatter: function (params: any[]) {
      let tooltipText = `${params[0].name}<br/>`;
      params.forEach(param => {
        // 所有值都显示为整数
        let value;
        if (typeof param.value === 'number') {
          value = Math.round(param.value).toString();
        } else {
          value = param.value;
        }
        tooltipText += `${param.marker}${param.seriesName}: ${value}<br/>`;
      });
      return tooltipText;
    }
  },
  grid: {
    left: "3%",
    right: "4%",
    bottom: "3%",
    top: "15%",
    containLabel: true
  },
  legend: {
    data: [] as string[],
    top: "5%",
    textStyle: { color: "#c0c4cc" }
  },
  xAxis: [
    {
      type: "category",
      data: [] as string[],
      axisTick: { alignWithLabel: true },
      axisLabel: { color: "#c0c4cc", fontSize: 10 }
    }
  ],
  yAxis: [
    {
      type: "value",
      axisLabel: { color: "#c0c4cc", fontSize: 10 },
      splitLine: { lineStyle: { color: "#3a5a8a", opacity: 0.3 } }
    }
  ],
  series: [] as any[]
};

// 柱状图配置
const statusBarChartOption = computed(() => {
  const currentDataType = barChartType.value as keyof typeof barChartData;
  const actualData = barChartData[currentDataType];
  const stdValue = standardValues[currentDataType];
  const standardData = Array(actualData.length).fill(stdValue);
  const xAxisData = ["R1", "R3", "R5", "R7", "R9", "R11", "R13", "R15"];

  const series = [
    {
      name: barChartType.value,
      type: "bar",
      barWidth: "30%",
      data: actualData,
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,
            color:
              barChartType.value === "超差辊"
                ? "#42b4ff"
                : barChartType.value === "公里数"
                  ? "#67c23a"
                  : "#e6a23c"
          },
          { offset: 1, color: "rgba(11, 41, 96, 0.8)" }
        ]),
        borderRadius: [5, 5, 0, 0],
        shadowColor:
          barChartType.value === "超差辊"
            ? "rgba(66, 180, 255, 0.5)"
            : barChartType.value === "公里数"
              ? "rgba(103, 194, 58, 0.5)"
              : "rgba(230, 162, 60, 0.5)",
        shadowBlur: 10
      }
    },
    {
      name: "标准值",
      type: "bar",
      barWidth: "30%",
      data: standardData,
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: "#ff7043" },
          { offset: 1, color: "rgba(255, 112, 67, 0.5)" }
        ]),
        borderRadius: [5, 5, 0, 0],
        shadowColor: "rgba(255, 112, 67, 0.5)",
        shadowBlur: 8
      }
    }
  ];

  return {
    ...baseBarOption,
    legend: {
      ...baseBarOption.legend,
      data: [barChartType.value, "标准值"]
    },
    xAxis: [
      {
        ...baseBarOption.xAxis[0],
        data: xAxisData,
        axisLine: { lineStyle: { color: "#3a5a8a" } }
      }
    ],
    yAxis: [
      {
        ...baseBarOption.yAxis[0],
        axisLine: { lineStyle: { color: "#3a5a8a" } },
        max: 50000,
        interval: 12500
      }
    ],
    series: series
  };
});

onBeforeMount(() => {
  useUserStore().setTagNav(data.value);
});

// 更新柱状图
const updateBarChart = () => {
  if (statusBarChartInstance) {
    const currentDataType = barChartType.value as keyof typeof barChartData;
    const actualData = barChartData[currentDataType];
    const stdValue = standardValues[currentDataType];
    const standardData = Array(actualData.length).fill(stdValue);

    statusBarChartInstance.setOption({
      legend: {
        data: [barChartType.value, "标准值"]
      },
      series: [
        {
          name: barChartType.value,
          data: actualData,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color:
                  barChartType.value === "超差辊"
                    ? "#42b4ff"
                    : barChartType.value === "公里数"
                      ? "#67c23a"
                      : "#e6a23c"
              },
              { offset: 1, color: "rgba(11, 41, 96, 0.8)" }
            ]),
            shadowColor:
              barChartType.value === "超差辊"
                ? "rgba(66, 180, 255, 0.5)"
                : barChartType.value === "公里数"
                  ? "rgba(103, 194, 58, 0.5)"
                  : "rgba(230, 162, 60, 0.5)"
          }
        },
        {
          name: "标准值",
          data: standardData
        }
      ]
    });
  }
};

// 线图配置 - 与图片匹配的数据和样式
const lineChartOption1 = computed(() => ({
  backgroundColor: "transparent",
  tooltip: {
    trigger: "axis",
    formatter: function (params: any) {
      let result = params[0].axisValue + '<br/>';
      params.forEach((param: any) => {
        // 所有值都显示为整数
        let value;
        if (typeof param.value === 'number') {
          value = Math.round(param.value).toString();
        } else {
          value = param.value;
        }
        result += param.marker + param.seriesName + ': ' + value + '<br/>';
      });
      return result;
    }
  },
  legend: {
    data: ["指标A", "指标B"],
    textStyle: { color: "#fff", fontSize: 12 },
    formatter: function (name: string) {
      return name === "指标A" ? "指标A" : "指标B";
    },
    selectedMode: false,
    icon: "circle",
    itemWidth: 8,
    itemHeight: 8,
    top: "5%",
    itemGap: 20
  },
  grid: {
    left: "5%",
    right: "5%",
    bottom: "10%",
    top: "25%",
    containLabel: true
  },
  xAxis: {
    type: "category",
    boundaryGap: false,
    data: ["T0", "T1", "T2", "T3", "T4", "T5", "T6", "T7", "T8", "T9"],
    axisLine: { lineStyle: { color: "#3a5a8a" } },
    axisLabel: { color: "#c0c4cc", fontSize: 10 },
    splitLine: { show: false }
  },
  yAxis: {
    type: "value",
    min: 0,
    max: 8,
    interval: 2,
    axisLabel: { color: "#c0c4cc", fontSize: 10 },
    splitLine: { lineStyle: { color: "#3a5a8a", opacity: 0.3 } },
    axisLine: { lineStyle: { color: "#3a5a8a" } }
  },
  series: [
    {
      name: "指标A",
      type: "line",
      smooth: true,
      symbolSize: 6,
      symbol: "circle",
      areaStyle: {
        opacity: 0.8,
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: "rgba(58, 218, 255, 0.8)" },
          { offset: 1, color: "rgba(11, 41, 96, 0.1)" }
        ])
      },
      emphasis: { focus: "series" },
      data: [5.2, 4.1, 4.3, 4.8, 4.2, 4.7, 5.5, 6.0, 5.2, 4.0],
      itemStyle: {
        color: "#5dd1fa",
        shadowColor: "rgba(93, 209, 250, 0.8)",
        shadowBlur: 10
      },
      lineStyle: {
        width: 3,
        shadowColor: "rgba(93, 209, 250, 0.8)",
        shadowBlur: 10
      }
    },
    {
      name: "指标B",
      type: "line",
      smooth: true,
      symbolSize: 6,
      symbol: "circle",
      areaStyle: {
        opacity: 0.4,
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: "rgba(150, 220, 90, 0.6)" },
          { offset: 1, color: "rgba(11, 41, 96, 0.1)" }
        ])
      },
      emphasis: { focus: "series" },
      data: [3.0, 2.1, 3.5, 4.0, 2.8, 2.1, 1.5, 2.3, 2.0, 1.8],
      itemStyle: {
        color: "#91cc75",
        shadowColor: "rgba(145, 204, 117, 0.8)",
        shadowBlur: 10
      },
      lineStyle: {
        width: 3,
        type: "dashed",
        shadowColor: "rgba(145, 204, 117, 0.8)",
        shadowBlur: 5
      }
    }
  ]
}));

const baseLineOption = {
  tooltip: {
    trigger: "axis",
    formatter: function (params: any) {
      let result = params[0].axisValue + '<br/>';
      params.forEach((param: any) => {
        // 所有值都显示为整数
        let value;
        if (typeof param.value === 'number') {
          value = Math.round(param.value).toString();
        } else {
          value = param.value;
        }
        result += param.marker + param.seriesName + ': ' + value + '<br/>';
      });
      return result;
    }
  },
  legend: {
    data: [] as string[],
    textStyle: { color: "#c0c4cc" },
    icon: "circle",
    itemWidth: 8,
    itemHeight: 8,
    top: "5%",
    itemGap: 20
  },
  grid: {
    left: "5%",
    right: "5%",
    bottom: "10%",
    top: "25%",
    containLabel: true
  },
  xAxis: {
    type: "category",
    boundaryGap: false,
    data: [] as string[],
    axisLabel: { color: "#c0c4cc", fontSize: 10 },
    splitLine: { show: false }
  },
  yAxis: {
    type: "value",
    axisLabel: { color: "#c0c4cc", fontSize: 10 },
    splitLine: { lineStyle: { color: "#3a5a8a", opacity: 0.3 } },
    min: 0,
    max: 8
  },
  series: [] as any[]
};

// --- SVG交互 ---
const onSvgLoaded = () => {
  console.log("SVG图片加载完成");

  // 简化SVG加载事件，暂时移除SVG DOM操作
  try {
    // SVG加载成功
    console.log("SVG加载成功");
  } catch (error) {
    console.error("SVG操作失败:", error);
  }
};

// --- 初始化图表 ---
const initCharts = () => {
  try {
    if (statusBarChartRef.value && !statusBarChartInstance) {
      statusBarChartInstance = echarts.init(statusBarChartRef.value);
      statusBarChartInstance.setOption(statusBarChartOption.value);
    }

    const lineChartOption = lineChartOption1.value;

    if (lineChart1Ref.value && !lineChart1Instance) {
      lineChart1Instance = echarts.init(lineChart1Ref.value);
      lineChart1Instance.setOption(lineChartOption);
    }
    if (lineChart2Ref.value && !lineChart2Instance) {
      lineChart2Instance = echarts.init(lineChart2Ref.value);
      lineChart2Instance.setOption(lineChartOption);
    }
    if (lineChart3Ref.value && !lineChart3Instance) {
      lineChart3Instance = echarts.init(lineChart3Ref.value);
      lineChart3Instance.setOption(lineChartOption);
    }
    if (lineChart4Ref.value && !lineChart4Instance) {
      lineChart4Instance = echarts.init(lineChart4Ref.value);
      lineChart4Instance.setOption(lineChartOption);
    }
  } catch (error) {
    console.error("图表初始化失败:", error);
  }
};

// 动态更新数据
const updateData = () => {
  // 更新生产统计信息（小幅度波动）
  productionStats.dailyOutput = parseFloat(
    (1028.3 + (Math.random() * 10 - 5)).toFixed(1)
  );
  productionStats.actualHourlyOutput = parseFloat(
    (152.5 + (Math.random() * 5 - 2.5)).toFixed(1)
  );
  productionStats.hourlyOutput = parseFloat(
    (135.0 + (Math.random() * 4 - 2)).toFixed(1)
  );
  productionStats.processSpeed = parseFloat(
    (210.7 + (Math.random() * 8 - 4)).toFixed(1)
  );

  // 更新张力信息（小幅度波动）
  tensionInfo.actual = parseFloat(
    (2.5 + (Math.random() * 0.6 - 0.3)).toFixed(1)
  );
};

const resizeCharts = () => {
  statusBarChartInstance?.resize();
  lineChart1Instance?.resize();
  lineChart2Instance?.resize();
  lineChart3Instance?.resize();
  lineChart4Instance?.resize();
};

// --- 生命周期钩子 ---
let updateTimer: number | null = null;

// Refs for ZLGDH specific live data (similar to continuousrefund/index.vue)
const zlgdhEntSpeed = ref<number>(0);
const zlgdhProcessSpeed = ref<number>(0);
const zlgdhExitSpeed = ref<number>(0);

const zlgdhInletLooper = ref<number>(0);
const zlgdhMiddleLooper = ref<number>(0);
const zlgdhExportLooper = ref<number>(0);

const zlgdhInletLooperTime = ref<string>("0 min");
const zlgdhMiddleLooperTime = ref<string>("0 min");
const zlgdhExportLooperTime = ref<string>("0 min");
const inletLooper = ref<number>(0);
const middleLooper = ref<number>(0);

const zlgdhUncoilerLenA = ref<number>(0);
const zlgdhUncoilerLenB = ref<number>(0);
const zlgdhCoilerLenA = ref<number>(0);
const zlgdhCoilerLenB = ref<number>(0);
let tr: any = null;
let por: any = null;
let ti: any = null;

const zlgdhCpcWidth = ref<number>(0);
const zlgdhCpcWidthAlarm = ref<boolean>(false);
let interval: any = null;

// Refs for ZLGDH speed chart instances
let zlgdhSpeedChartEntInstance: echarts.ECharts | null = null;
let zlgdhSpeedChartProcessInstance: echarts.ECharts | null = null;
let zlgdhSpeedChartExitInstance: echarts.ECharts | null = null;

// 定时器变量
let colorUpdateTimer: number | null = null;

// Base options for ZLGDH speed gauges (adapt from CAL1630全线跟踪页面)
const ZlgdhSpeedBaseOption: any = {
  ent: { max: 500, segmentation1: 80, segmentation2: 300 }, // 入口段速度仪表盘配置
  process: { max: 500, segmentation1: 120, segmentation2: 300 }, // 工艺段速度仪表盘配置
  exit: { max: 500, segmentation1: 80, segmentation2: 300 } // 出口段速度仪表盘配置
};

const numberFormat = (number: any, precision: number = 0) => {
  if (number === undefined || number === null || String(number).trim() === "") {
    const zero = 0;
    return zero.toFixed(precision);
  }
  const num = parseFloat(String(number));
  if (isNaN(num)) {
    const zero = 0;
    return zero.toFixed(precision);
  }
  return num.toFixed(precision);
};

const numberFormat1 = (number: any) => {
  return number == undefined ? 0 : Number(parseFloat(number).toFixed(0));
};



const initZlgdhScoreChart = (
  chartId: string,
  value: number,
  type: "ent" | "process" | "exit"
) => {
  const chartDom = document.getElementById(chartId) as HTMLElement;
  if (!chartDom) return null;

  let speedChart = echarts.getInstanceByDom(chartDom);
  if (!speedChart) {
    speedChart = echarts.init(chartDom);
  }
  const baseOption = ZlgdhSpeedBaseOption[type];
  const option = {
    series: [
      {
        type: "gauge",
        center: ["50%", "50%"],
        radius: "80%",
        startAngle: 225,
        endAngle: -45,
        max: baseOption.max,
        axisLine: {
          roundCap: true,
          lineStyle: {
            width: 7,
            color: [
              [
                1,
                new echarts.graphic.LinearGradient(0, 1, 0.9, 1, [
                  { offset: 0, color: "#D64444" },
                  { offset: 0.2, color: "#D86E6D" },
                  { offset: 0.5, color: "#F1F3F4" },
                  { offset: 0.65, color: "#F1F3F4" },
                  { offset: 0.8, color: "#79ACF6" },
                  { offset: 1, color: "#1976FD" }
                ])
              ]
            ]
          }
        },
        pointer: {
          length: "90%",
          width: 2,
          color: "#FFFFFF"
        },
        axisTick: {
          distance: -14,
          length: 2,
          lineStyle: { color: "#4B83F7", width: 2 }
        },
        splitLine: {
          distance: -16,
          length: 6,
          lineStyle: { color: "#4B83F7", width: 2 }
        },
        axisLabel: {
          color: "#FFF",
          fontSize: 14,
          distance: -30,
          rotate: "tangential",
          formatter: function (value: any) {
            if (value === 0) {
              return "";
            } else if (value === baseOption.segmentation1) {
              return "";
            } else if (value === baseOption.segmentation2) {
              return "";
            } else if (value === baseOption.max) {
              return "";
            }
            return "";
          }
        },
        title: {
          offsetCenter: [0, "70%"],
          fontSize: 12,
          color: "#FFF"
        },
        detail: {
          fontSize: 18,
          offsetCenter: [0, "30%"],
          valueAnimation: true,
          formatter: function (value: any) {
            return `${Math.round(value)}`;
          },
          color: "#FFF"
        },
        data: [{ value: value, name: "mpm" }]
      }
    ]
  };
  speedChart.setOption(option);
  return speedChart;
};

// Main function to fetch and process all live data
const updateZlgdhLiveData = async () => {
  try {
    // 1. Fetch ItemTag Data (G_...NI values) - 使用CAL1630的API
    const itemTagResponse = await axios.get(
      "http://10.171.7.100:8090/restapi?name=CAL1630_itemtag"
    );
    itemTagData.value = itemTagResponse.data || {};
    const currentItemTags = itemTagData.value;

    // Update refs from itemTagData (mirroring CAL1630全线跟踪页面的getItemTag function)
    zlgdhEntSpeed.value = parseFloat(
      String(currentItemTags["G1_1803NI"] || "0")
    );
    zlgdhProcessSpeed.value = parseFloat(
      String(currentItemTags["G1_1801NI"] || "0")
    ); // CAL1630全线跟踪页面使用G1_1801NI for spmSpeed
    zlgdhExitSpeed.value = parseFloat(
      String(currentItemTags["G1_1800NI"] || "0")
    );
    let cenSpeed = parseFloat(String(currentItemTags['G1_1802NI'] || '0')); // CAL1630全线跟踪页面cenSpeed

    zlgdhUncoilerLenA.value = parseFloat(
      String(currentItemTags["G201_529NI"] || "0")
    );
    zlgdhUncoilerLenB.value = parseFloat(
      String(currentItemTags["G201_536NI"] || "0")
    );
    zlgdhCoilerLenA.value = parseFloat(
      String(currentItemTags["G414_448NI"] || "0")
    );
    zlgdhCoilerLenB.value = parseFloat(
      String(currentItemTags["G414_457NI"] || "0")
    );
    zlgdhCpcWidth.value = parseFloat(
      String(currentItemTags["G17_405NI"] || "0")
    );

    // 2. Fetch ZoneTrack Data (zones, loop, tr, por, weld) - 使用CAL1630的API
    const zoneTrackResponse = await axios.get(
      "http://10.171.7.100:8090/restapi?name=CAL1630_zonetrk"
    );
    zoneTrackData.value = zoneTrackResponse.data || {};
    const currentZoneTracks = zoneTrackData.value;

    if (currentZoneTracks.loop && currentZoneTracks.loop.length >= 3) {
      // CAL1630全线跟踪页面的活套数据处理方式
      zlgdhInletLooper.value = parseFloat(String(currentZoneTracks.loop[2] || "0")); // 入口活套
      zlgdhMiddleLooper.value = parseFloat(String(currentZoneTracks.loop[1] || "0")); // 中间活套
      zlgdhExportLooper.value = parseFloat(String(currentZoneTracks.loop[0] || "0")); // 出口活套
    }

    // Calculate Looper Times (now that speeds and loop values are available)
    // 使用CAL1630全线跟踪页面的sleeveDeclineTime调用方式
    zlgdhInletLooperTime.value = sleeveDeclineTime(
      technologicalName,
      "entrance",
      zlgdhEntSpeed.value,
      zlgdhProcessSpeed.value,
      zlgdhInletLooper.value
    );
    zlgdhMiddleLooperTime.value = sleeveDeclineTime(
      technologicalName,
      "middle",
      zlgdhProcessSpeed.value,
      zlgdhExitSpeed.value,
      zlgdhMiddleLooper.value
    );
    zlgdhExportLooperTime.value = sleeveDeclineTime(
      technologicalName,
      "exit",
      zlgdhProcessSpeed.value,
      zlgdhExitSpeed.value,
      zlgdhExportLooper.value
    );

    // Update ECharts speed gauges with new values
    if (zlgdhSpeedChartEntInstance)
      zlgdhSpeedChartEntInstance.setOption({
        series: [{ data: [{ value: zlgdhExitSpeed.value }] }]
      });
    if (zlgdhSpeedChartProcessInstance)
      zlgdhSpeedChartProcessInstance.setOption({
        series: [{ data: [{ value: zlgdhProcessSpeed.value }] }]
      });
    if (zlgdhSpeedChartExitInstance)
      zlgdhSpeedChartExitInstance.setOption({
        series: [{ data: [{ value: zlgdhEntSpeed.value }] }]
      });
  } catch (error) {
    console.error("Error in updateZlgdhLiveData:", error);
  }

  // Update other existing data (for top panel charts, if any specific logic beyond direct binding was here)
  updateData();
};

onBeforeMount(() => {
  interval = setInterval(() => {
    getZoneTrk();
  }, 2000);
});

const getZoneTrk = async () => {
  let param = {
    name: "CAL1630_zonetrk"
  };
  rollingSimulationApi.rest(param).then(res => {
    let zones = res.data.zoneno;
    weldMachineState(`${technologicalName}-welder`, res.data.weld);
    inletLooper.value = res.data["loop"][0];
    middleLooper.value = res.data["loop"][1];
    exportLooper.value = res.data["loop"][2];
    let trKey = `${technologicalName}-ZONE_tr${res.data.tr}`;
    let trpathKey = trKey + "_path";
    let porKey = `${technologicalName}-ZONE_por${res.data.por}`;
    let porpathKey = porKey + "_path";
    var arr = Object.keys(zones);
    /**开卷机和卷取机 */
    if (tr === null || tr !== res.data.tr) {
      tr = res.data.tr;
      refreshSVG(zones[arr.length - 1].ti % 10, trpathKey);
      refreshGraphical(zones[arr.length - 1].ti % 10, trKey);
      initialSVG(technologicalName, "tr", res.data.tr);
    }
    if (por === null || por !== res.data.por) {
      por = res.data.por;
      if (res.data.por === 0) {
        initialSVG(technologicalName, "por", "1");
        initialSVG(technologicalName, "por", "2");
      }
    }
    if (ti === null || ti !== zones[0].ti) {
      ti = zones[0].ti;
      refreshSVG(zones[0].ti % 10, porpathKey);
      refreshGraphical(zones[0].ti % 10, porKey);
      initialSVG(technologicalName, "por", res.data.por);
    }
    for (let i in zones) {
      let pathkey = `${technologicalName}-ZONE${i}`;
      refreshSVG(zones[i].ti % 10, pathkey);
    }
  });
};

onMounted(() => {
  nextTick(() => {
    setTimeout(() => {
      initCharts(); // Existing charts for top panel

      // Initialize ZLGDH speed gauges
      zlgdhSpeedChartEntInstance = initZlgdhScoreChart(
        "zlgdh_speed_ent",
        zlgdhExitSpeed.value,
        "exit"
      );
      zlgdhSpeedChartProcessInstance = initZlgdhScoreChart(
        "zlgdh_speed_process",
        zlgdhProcessSpeed.value,
        "process"
      );
      zlgdhSpeedChartExitInstance = initZlgdhScoreChart(
        "zlgdh_speed_exit",
        zlgdhEntSpeed.value,
        "ent"
      );

      // Initialize line charts for real-time data
      initLineCharts();

      // Initial fetch and update of all live data
      updateZlgdhLiveData();
      // Removed previous direct axios.get for itemtag/zonetrk as they are now inside updateZlgdhLiveData
    }, 100);
  });

  window.addEventListener("resize", () => {
    resizeCharts(); // Resize top panel charts
    zlgdhSpeedChartEntInstance?.resize();
    zlgdhSpeedChartProcessInstance?.resize();
    zlgdhSpeedChartExitInstance?.resize();
  });

  fetchTableData();

  // Set up periodic updates
  updateTimer = window.setInterval(updateZlgdhLiveData, 3000);

  // 设置API数据轮询定时器，每5秒更新一次
  colorUpdateTimer = window.setInterval(() => {
    fetchAISetValues();
  }, 5000);

  // 调用fetchAISetValues方法
  fetchAISetValues();

  // 延迟检查并设置默认选择（作为备用方案）
  setTimeout(() => {
    setDefaultSelections();
  }, 3000);

  // 测试SVG元素查找和颜色更新功能
  waitForSvgLoad(() => {
    testSvgElementManipulation();
  });
});
// 获取表格数据
const fetchTableData = async () => {
  try {
    const params: any = {
      pageIndex: String(pagination.currentPage),
      pageSize: String(pagination.pageSize),
    };


    console.log('Fetching data with params:', params);
    const response = await zlgdhApi.getData(params);
    console.log('API Response:', response);

    // Correctly access data from response.data if 'response' is an AxiosResponse
    const responseData = response.data;

    if (responseData && responseData.data && Array.isArray(responseData.data.records)) {
      tableData.value = responseData.data.records.map((item: any) => ({
        ...item, // Keep other original fields if needed for detail view
      }));

      ElMessage.success(responseData.msg || '查询成功');
    } else {
      ElMessage.info(responseData?.msg || (response as any)?.msg || '未查询到数据或响应格式不正确');
      tableData.value = [];
    }
  } catch (error: any) {
    console.error('获取数据失败:', error);
    // Try to get error message from error.response.data.msg or error.data.msg
    const errorMessage = error.response?.data?.msg || error.data?.msg || error.msg || error.message || '获取数据失败';
    ElMessage.error(errorMessage);
    tableData.value = [];
  }
};

onUnmounted(() => {
  window.removeEventListener("resize", resizeCharts);
  statusBarChartInstance?.dispose();
  lineChart1Instance?.dispose();
  lineChart2Instance?.dispose();
  lineChart3Instance?.dispose();
  lineChart4Instance?.dispose();

  zlgdhSpeedChartEntInstance?.dispose();
  zlgdhSpeedChartProcessInstance?.dispose();
  zlgdhSpeedChartExitInstance?.dispose();

  if (updateTimer !== null) {
    clearInterval(updateTimer);
  }

  // 清理颜色更新定时器
  if (colorUpdateTimer !== null) {
    clearInterval(colorUpdateTimer);
  }

  // 清理实时数据轮询定时器
  stopRealDataPolling(1);
  stopRealDataPolling(2);
  stopRealDataPolling(3);
});

// --- API data storage and SVG state tracking (as per CAL2150Track.vue logic) ---
const itemTagData = ref<any>({});
const zoneTrackData = ref<any>({});
const technologicalName = "CAL1630";

let prevTr: string | null = null;
let prevPor: string | null = null;
let prevTi: string | null = null;



// 获取AI设定值接口
async function fetchAISetValues() {
  const param = {
    action: 'get_tags',
    operator: 'abc',
    terminal: 'FM_01',
    body: [
      { tagName: 'SLIP_ALARM_TAG', timestamp: 0 },
    ],
  };
  try {
    const res = await CAL1630TempCtrlApi.getTableData(param);

    // 处理API响应数据，更新SVG元素颜色和下拉框选项
    if (res && res.data && res.data.results && res.data.results[0] && res.data.results[0].value && res.data.results[0].value[0]) {
      const apiData = res.data.results[0].value[0];

      updateSvgColorsBasedOnApiData(apiData);
      updateDropdownOptions(apiData);

      // 延迟检查并设置默认选择
      setTimeout(() => {
        setDefaultSelections();
      }, 1000);
    }
  } catch (e: any) {
    console.error('AI设定值接口调用失败', e);
  }
}

// 根据API数据更新SVG元素颜色
const updateSvgColorsBasedOnApiData = (apiData: any) => {
  waitForSvgLoad(() => {
    // 遍历API响应中的每个字段
    Object.keys(apiData).forEach(fieldName => {
      const fieldValue = apiData[fieldName];

      // 直接通过字段名称查找对应的SVG元素
      const svgElement = document.getElementById(fieldName);

      if (svgElement) {
        // 如果字段值为1，则将对应的SVG元素变为红色
        if (fieldValue === 1) {
          // 根据元素类型设置颜色
          if (svgElement.tagName === 'ellipse' || svgElement.tagName === 'circle' || svgElement.tagName === 'rect') {
            svgElement.style.fill = '#FFFF00'; // 亮黄色
          } else if (svgElement.tagName === 'path') {
            svgElement.style.stroke = '#FFFF00'; // 亮黄色
            svgElement.style.strokeWidth = '3px';
          } else if (svgElement.tagName === 'g') {
            // 如果是组元素，更新其子元素
            const childElements = svgElement.querySelectorAll('path, ellipse, circle, rect');
            childElements.forEach((child: Element) => {
              if (child.tagName === 'ellipse' || child.tagName === 'circle' || child.tagName === 'rect') {
                (child as HTMLElement).style.fill = '#FFFF00';
              } else if (child.tagName === 'path') {
                (child as HTMLElement).style.stroke = '#FFFF00';
                (child as HTMLElement).style.strokeWidth = '3px';
              }
            });
          }
        } else {
          // 如果字段值不为1，恢复为原本的绿色
          if (svgElement.tagName === 'ellipse' || svgElement.tagName === 'circle' || svgElement.tagName === 'rect') {
            svgElement.style.fill = '#00FF00'; // 恢复为绿色
          } else if (svgElement.tagName === 'path') {
            svgElement.style.stroke = '#00FF00'; // 恢复为绿色
            svgElement.style.strokeWidth = '2px';
          } else if (svgElement.tagName === 'g') {
            // 如果是组元素，恢复其子元素为绿色
            const childElements = svgElement.querySelectorAll('path, ellipse, circle, rect');
            childElements.forEach((child: Element) => {
              if (child.tagName === 'ellipse' || child.tagName === 'circle' || child.tagName === 'rect') {
                (child as HTMLElement).style.fill = '#00FF00';
              } else if (child.tagName === 'path') {
                (child as HTMLElement).style.stroke = '#00FF00';
                (child as HTMLElement).style.strokeWidth = '2px';
              }
            });
          }
        }
      }
    });
  });
};

// 设置默认选择
const setDefaultSelections = () => {
  // 如果下拉框1有选项但没有选择值，选择第一个
  if (torqueOptions1.value.length > 0 && !torqueSelect1.value) {
    torqueSelect1.value = torqueOptions1.value[0].value;
    handleTorqueSelect1Change(torqueOptions1.value[0].value);
  }

  // 如果下拉框2有选项但没有选择值，选择第一个
  if (torqueOptions2.value.length > 0 && !torqueSelect2.value) {
    torqueSelect2.value = torqueOptions2.value[0].value;
    handleTorqueSelect2Change(torqueOptions2.value[0].value);
  }

  // 如果下拉框3有选项但没有选择值，选择第一个
  if (torqueOptions3.value.length > 0 && !torqueSelect3.value) {
    torqueSelect3.value = torqueOptions3.value[0].value;
    handleTorqueSelect3Change(torqueOptions3.value[0].value);
  }
};

// 根据API数据更新下拉框选项
const updateDropdownOptions = (apiData: any) => {
  // 初始化选项数组
  const options1: Array<{ label: string, value: string }> = []; // 入口段 - BR7, BR8, BR9
  const options2: Array<{ label: string, value: string }> = []; // 工艺段 - BR3, BR6 和其他
  const options3: Array<{ label: string, value: string }> = []; // 出口段 - BR1, BR2

  // 遍历API响应中的每个字段
  Object.keys(apiData).forEach(fieldName => {
    const fieldValue = apiData[fieldName];

    // 只处理值为1的字段
    if (fieldValue === 1) {
      const option = { label: fieldName, value: fieldName };

      // 根据字段名分类到不同的下拉框
      if (fieldName.includes('BR7') || fieldName.includes('BR8') || fieldName.includes('BR9')) {
        options1.push(option);
      } else if (fieldName.includes('BR1') || fieldName.includes('BR2')) {
        options3.push(option);
      } else {
        options2.push(option);
      }
    }
  });

  // 更新下拉框选项
  torqueOptions1.value = options1;
  torqueOptions2.value = options2;
  torqueOptions3.value = options3;

  // 自动选择第一个选项
  if (options1.length > 0 && !torqueSelect1.value) {
    torqueSelect1.value = options1[0].value;
    // 触发选择变化事件
    handleTorqueSelect1Change(options1[0].value);
  }

  if (options2.length > 0 && !torqueSelect2.value) {
    torqueSelect2.value = options2[0].value;
    // 触发选择变化事件
    handleTorqueSelect2Change(options2[0].value);
  }

  if (options3.length > 0 && !torqueSelect3.value) {
    torqueSelect3.value = options3[0].value;
    // 触发选择变化事件
    handleTorqueSelect3Change(options3[0].value);
  }
};

// 等待SVG加载完成的函数
const waitForSvgLoad = (callback: () => void, maxAttempts = 20) => {
  let attempts = 0;

  const checkSvgReady = () => {
    attempts++;
    const svgContainer = document.querySelector('.svg svg');
    const testElement = document.getElementById('1630_BR4.1_1_1');

    if (svgContainer && testElement) {
      console.log(`SVG加载完成，尝试次数: ${attempts}`);
      callback();
    } else if (attempts < maxAttempts) {
      console.log(`SVG未准备好，等待中... 尝试次数: ${attempts}`);
      setTimeout(checkSvgReady, 500);
    } else {
      console.log('SVG加载超时，继续执行回调');
      callback();
    }
  };

  checkSvgReady();
};

// 测试SVG元素查找和颜色更新功能
const testSvgElementManipulation = () => {
  console.log('开始测试SVG元素操作');

  // 获取SVG容器元素
  const svgContainer = document.querySelector('.svg svg');
  if (!svgContainer) {
    console.log('测试失败：未找到SVG容器元素');
    return;
  }

  console.log('SVG容器找到:', svgContainer);
  console.log('SVG容器内容:', svgContainer.innerHTML.substring(0, 500));

  // 尝试查找SVG symbol元素
  const symbolElement = document.querySelector('#svg-CAL1630');
  if (symbolElement) {
    console.log('找到SVG symbol元素:', symbolElement);
  }

  // 查找一个已知的SVG元素进行测试
  let testElement = document.getElementById('1630_BR4.1_1_1');
  if (testElement) {
    console.log('找到测试元素:', testElement.id);
    if (testElement.tagName === 'ellipse' || testElement.tagName === 'circle' || testElement.tagName === 'rect') {
      testElement.style.fill = '#00FF00'; // 绿色
      console.log('测试元素颜色已更新为绿色');
    } else if (testElement.tagName === 'path') {
      testElement.style.stroke = '#00FF00'; // 绿色
      testElement.style.strokeWidth = '5px';
      console.log('测试路径颜色已更新为绿色');
    }
  } else {
    console.log('未找到测试元素 1630_BR4.1_1_1');

    // 尝试在SVG容器内查找
    if (svgContainer) {
      testElement = svgContainer.querySelector('#1630_BR4.1_1_1') as HTMLElement;
      if (testElement) {
        console.log('在SVG容器内找到测试元素:', testElement.id);
        if (testElement.tagName === 'ellipse' || testElement.tagName === 'circle' || testElement.tagName === 'rect') {
          testElement.style.fill = '#00FF00'; // 绿色
          console.log('测试元素颜色已更新为绿色');
        } else if (testElement.tagName === 'path') {
          testElement.style.stroke = '#00FF00'; // 绿色
          testElement.style.strokeWidth = '5px';
          console.log('测试路径颜色已更新为绿色');
        }
      }
    }

    // 显示所有可用的SVG元素
    const allElements = document.querySelectorAll('[id*="1630_BR"]');
    console.log(`找到 ${allElements.length} 个包含1630_BR的元素:`);
    allElements.forEach((element, index) => {
      if (index < 5) {
        console.log(`元素 ${index + 1}: ${element.id}, 标签: ${element.tagName}`);
      }
    });
  }
};

// 处理关键辊选择变化的函数
const handleTorqueSelect1Change = async (value: string) => {
  // 停止之前的轮询
  stopRealDataPolling(1);

  if (value) {
    await callGetDicPropCode(value, 1);
  }
};

const handleTorqueSelect2Change = async (value: string) => {
  // 停止之前的轮询
  stopRealDataPolling(2);

  if (value) {
    await callGetDicPropCode(value, 2);
  }
};

const handleTorqueSelect3Change = async (value: string) => {
  // 停止之前的轮询
  stopRealDataPolling(3);

  if (value) {
    await callGetDicPropCode(value, 3);
  }
};

// 调用getDicPropCode API的函数
const callGetDicPropCode = async (fieldName: string, chartIndex: number) => {
  try {
    // 解析字段名，例如: 1630_BR1_1_1
    const parts = fieldName.split('_');
    if (parts.length === 4) {
      const [dicLineNo, dicZone, dicRollType, dicRollNo] = parts;

      const params = {
        dicLineNo: dicLineNo,
        dicZone: dicZone,
        dicRollType: dicRollType,
        dicRollNo: dicRollNo
      };

      console.log('调用getDicPropCode API，参数:', params);
      const response = await CAL1630TempCtrlApi.getDicPropCode(params);
      console.log('getDicPropCode API 响应:', response);

      // 如果API调用成功，继续获取CAL1630_RealData
      if (response && response.data) {
        await fetchCAL1630RealData(response, chartIndex);
      }
    } else {
      console.log('字段名格式不正确，无法解析:', fieldName);
    }
  } catch (error) {
    console.error('调用getDicPropCode API失败:', error);
  }
};

// 获取CAL1630_RealData的函数
const fetchCAL1630RealData = async (getDicPropCodeResponse: any, chartIndex: number) => {
  try {
    // 从getDicPropCode响应中提取 dicPropCode / dicPropName / dicPropType
    const dicPropCodeValues: string[] = [];
    const dicPropNameValues: string[] = [];
    const dicPropTypeValues: number[] = [];
    console.log("getDicPropCode响应:", getDicPropCodeResponse);

    // 根据用户反馈，从getDicPropCodeResponse.data.data中提取dicPropCode和dicPropName值
    if (getDicPropCodeResponse.data && getDicPropCodeResponse.data.data) {
      const dataArray = getDicPropCodeResponse.data.data;

      // 确保是数组
      if (Array.isArray(dataArray) && dataArray.length > 0) {
        console.log(`找到${dataArray.length}条数据:`, dataArray);

        // 遍历数组，提取每条数据中的dicPropCode和dicPropName
        dataArray.forEach((item: any, index: number) => {
          if (item && item.dicPropCode) {
            dicPropCodeValues.push(item.dicPropCode);
            console.log(`第${index + 1}条数据的dicPropCode:`, item.dicPropCode);
          }
          if (item && item.dicPropName) {
            dicPropNameValues.push(item.dicPropName);
            console.log(`第${index + 1}条数据的dicPropName:`, item.dicPropName);
          }
          if (item && (item.dicPropType !== undefined && item.dicPropType !== null)) {
            dicPropTypeValues.push(Number(item.dicPropType));
            console.log(`第${index + 1}条数据的dicPropType:`, item.dicPropType);
          }
        });
      } else {
        console.log('data不是数组或为空:', dataArray);
      }
    } else {
      console.log('未找到data字段或data字段为空');
    }

    // 如果找到了dicPropCode值，则开始轮询
    if (dicPropCodeValues.length > 0) {
      console.log('从getDicPropCode响应中提取的dicPropCode值:', dicPropCodeValues);
      console.log('从getDicPropCode响应中提取的dicPropName值:', dicPropNameValues);

      // 打印每个字段的含义，帮助理解数据结构
      dicPropNameValues.forEach((name, index) => {
        console.log(`字段${index + 1}: ${name} (${dicPropCodeValues[index]})`);
      });

      // 根据chartIndex设置对应的dicPropCode和dicPropName值
      if (chartIndex === 1) {
        currentDicPropCodes1.value = dicPropCodeValues;
        currentDicPropNames1.value = dicPropNameValues;
        currentDicPropTypes1.value = dicPropTypeValues;
        startRealDataPolling(1);
      } else if (chartIndex === 2) {
        currentDicPropCodes2.value = dicPropCodeValues;
        currentDicPropNames2.value = dicPropNameValues;
        currentDicPropTypes2.value = dicPropTypeValues;
        startRealDataPolling(2);
      } else if (chartIndex === 3) {
        currentDicPropCodes3.value = dicPropCodeValues;
        currentDicPropNames3.value = dicPropNameValues;
        currentDicPropTypes3.value = dicPropTypeValues;
        startRealDataPolling(3);
      }
    } else {
      console.log('未从getDicPropCode响应中找到dicPropCode值');
    }
  } catch (error) {
    console.error('获取CAL1630_RealData失败:', error);
  }
};

// 开始实时数据轮询
const startRealDataPolling = (chartIndex: number) => {
  // 先停止之前的轮询
  stopRealDataPolling(chartIndex);

  // 清空之前的数据
  if (chartIndex === 1) {
    realData1.value = [];
  } else if (chartIndex === 2) {
    realData2.value = [];
  } else if (chartIndex === 3) {
    realData3.value = [];
  }

  // 立即执行一次数据获取
  pollRealData(chartIndex);

  // 设置定时器，每秒轮询一次
  const timer = setInterval(() => {
    pollRealData(chartIndex);
  }, 1000);

  // 保存定时器引用
  if (chartIndex === 1) {
    realDataTimer1.value = timer;
  } else if (chartIndex === 2) {
    realDataTimer2.value = timer;
  } else if (chartIndex === 3) {
    realDataTimer3.value = timer;
  }
};

// 停止实时数据轮询
const stopRealDataPolling = (chartIndex: number) => {
  let timer: NodeJS.Timeout | null = null;

  if (chartIndex === 1) {
    timer = realDataTimer1.value;
    realDataTimer1.value = null;
  } else if (chartIndex === 2) {
    timer = realDataTimer2.value;
    realDataTimer2.value = null;
  } else if (chartIndex === 3) {
    timer = realDataTimer3.value;
    realDataTimer3.value = null;
  }

  if (timer) {
    clearInterval(timer);
  }
};

// 轮询获取实时数据
const pollRealData = async (chartIndex: number) => {
  try {
    let dicPropCodes: string[] = [];
    let dicPropTypes: number[] = [];
    
    // 获取对应的dicPropCode值
    if (chartIndex === 1) {
      dicPropCodes = currentDicPropCodes1.value;
      dicPropTypes = currentDicPropTypes1.value;
    } else if (chartIndex === 2) {
      dicPropCodes = currentDicPropCodes2.value;
      dicPropTypes = currentDicPropTypes2.value;
    } else if (chartIndex === 3) {
      dicPropCodes = currentDicPropCodes3.value;
      dicPropTypes = currentDicPropTypes3.value;
    }

    if (dicPropCodes.length === 0) {
      return;
    }

    // 调用CAL1630_RealData API
    const realDataResponse = await axios.get('http://10.171.7.100:8090/restapi?name=CAL1630_RealData');

    if (realDataResponse.data) {
      const realData = realDataResponse.data;
      const currentTime = new Date().toLocaleTimeString();
      const values: number[] = [];

      // 遍历dicPropCode值，在realData中查找对应的字段
      dicPropCodes.forEach((propCode: string) => {
        if (realData[propCode] !== undefined) {
          // 将所有数值转换为整数
          const value = Math.round(realData[propCode]);
          values.push(value);
          console.log(`图表${chartIndex} - 找到字段 ${propCode} 的值:`, realData[propCode], `转换为整数:`, value);
        } else {
          values.push(0); // 如果找不到值，设为0
          console.log(`图表${chartIndex} - 未找到字段 ${propCode} 在CAL1630_RealData中`);
        }
      });

      // 计算新的速度设定mpm值
      // 根据 dicPropNames 来识别各个字段
      if (values.length >= 4) {
        let dicPropNames: string[] = [];
        if (chartIndex === 1) {
          dicPropNames = currentDicPropNames1.value;
        } else if (chartIndex === 2) {
          dicPropNames = currentDicPropNames2.value;
        } else if (chartIndex === 3) {
          dicPropNames = currentDicPropNames3.value;
        }

        // 根据 dicPropType 来识别各个值（1:设定速度 2:实际速度 3:实际转矩 4:实际速度mpm）
        let speedSetting = 0;
        let actualSpeed = 0;
        let actualSpeedMpm = 0;
        let actualTorque = 0;

        dicPropCodes.forEach((_, index) => {
          const value = Math.round(values[index] || 0);
          const type = (dicPropTypes && dicPropTypes[index]) ? Number(dicPropTypes[index]) : undefined;
          if (type === 1) {
            speedSetting = value;
          } else if (type === 2) {
            actualSpeed = value;
          } else if (type === 3) {
            actualTorque = value;
          } else if (type === 4) {
            actualSpeedMpm = value;
          } else {
            // 兜底：如果没有type，按名称再判别一次
            const name = dicPropNames[index] || '';
            const lname = name.toLowerCase();
            if (name.includes('设定') || lname.includes('set')) speedSetting = value;
            else if (name.includes('实际') && !lname.includes('mpm')) actualSpeed = value;
            else if (lname.includes('mpm')) actualSpeedMpm = value;
            else if (name.includes('转矩') || lname.includes('torque')) actualTorque = value;
          }
        });

        console.log(`图表${chartIndex} - 原始数据:`, {
          speedSetting,
          actualSpeed,
          actualSpeedMpm,
          actualTorque,
          dicPropNames
        });

        // 计算新的速度设定mpm = 速度设定 * 速度实际mpm / 速度实际
        let calculatedSpeedSettingMpm = 0;
        if (actualSpeed !== 0) {
          calculatedSpeedSettingMpm = Math.round(speedSetting * actualSpeedMpm / actualSpeed);
        }

        console.log(`图表${chartIndex} - 计算后的速度设定mpm:`, calculatedSpeedSettingMpm);
        // 打印提取的速度相关值（附带横轴时间）
        console.log(
          `时间: ${currentTime} | 图表${chartIndex} 提取值 -> 速度设定: ${Math.round(speedSetting)}, 速度实际: ${Math.round(actualSpeed)}, 速度实际mpm: ${Math.round(actualSpeedMpm)}`
        );

        // 重新组织数据：速度设定mpm（计算值）、实际转矩、速度实际mpm
        // 确保所有值都是整数
        const newValues = [
          Math.round(calculatedSpeedSettingMpm),
          Math.round(actualTorque),
          Math.round(actualSpeedMpm)
        ];

        console.log(`图表${chartIndex} - 最终数据:`, newValues);

        // 保存数据
        const dataPoint = {
          time: currentTime,
          values: newValues
        };

        if (chartIndex === 1) {
          realData1.value.push(dataPoint);
          // 保持最近30个数据点
          if (realData1.value.length > 30) {
            realData1.value.shift();
          }
          updateLineChart(1);
        } else if (chartIndex === 2) {
          realData2.value.push(dataPoint);
          if (realData2.value.length > 30) {
            realData2.value.shift();
          }
          updateLineChart(2);
        } else if (chartIndex === 3) {
          realData3.value.push(dataPoint);
          if (realData3.value.length > 30) {
            realData3.value.shift();
          }
          updateLineChart(3);
        }
      } else {
        // 如果数据不足4个，使用原始数据，但添加警告
        console.warn(`图表${chartIndex} - 数据不足4个，使用原始数据:`, values);
        // 确保所有值都是整数
        const roundedValues = values.map(value => Math.round(value));
        const dataPoint = {
          time: currentTime,
          values: roundedValues
        };

        if (chartIndex === 1) {
          realData1.value.push(dataPoint);
          if (realData1.value.length > 30) {
            realData1.value.shift();
          }
          updateLineChart(1);
        } else if (chartIndex === 2) {
          realData2.value.push(dataPoint);
          if (realData2.value.length > 30) {
            realData2.value.shift();
          }
          updateLineChart(2);
        } else if (chartIndex === 3) {
          realData3.value.push(dataPoint);
          if (realData3.value.length > 30) {
            realData3.value.shift();
          }
          updateLineChart(3);
        }
      }
    }
  } catch (error) {
    console.error(`图表${chartIndex} - 获取CAL1630_RealData失败:`, error);
  }
};

// 更新折线图
const updateLineChart = (chartIndex: number) => {
  let chartInstance: echarts.ECharts | null = null;
  let data: Array<{ time: string, values: number[] }> = [];
  let dicPropCodes: string[] = [];
  let dicPropNames: string[] = [];

  if (chartIndex === 1) {
    chartInstance = lineChart1Instance;
    data = realData1.value;
    dicPropCodes = currentDicPropCodes1.value;
    dicPropNames = currentDicPropNames1.value;
  } else if (chartIndex === 2) {
    chartInstance = lineChart2Instance;
    data = realData2.value;
    dicPropCodes = currentDicPropCodes2.value;
    dicPropNames = currentDicPropNames2.value;
  } else if (chartIndex === 3) {
    chartInstance = lineChart3Instance;
    data = realData3.value;
    dicPropCodes = currentDicPropCodes3.value;
    dicPropNames = currentDicPropNames3.value;
  }

  if (!chartInstance || data.length === 0) {
    return;
  }

  const times = data.map(item => item.time);

  // 根据新的数据结构创建series
  // 现在只显示三条线：速度设定mpm（计算值）、实际转矩、速度实际mpm
  const seriesNames = ['速度设定mpm', '实际转矩', '速度实际mpm'];
  const colors = ['#5dd1fa', '#91cc75', '#ff6b6b']; // 蓝色、绿色、红色

  // 计算速度数据的最小值，用于动态调整右侧Y轴
  const speedData = data.map(item => [Math.round(item.values[0] || 0), Math.round(item.values[2] || 0)]).flat(); // 速度设定mpm和速度实际mpm
  const minSpeed = Math.min(...speedData);
  const maxSpeed = Math.max(...speedData);

  // 如果速度有负值，动态调整右侧Y轴的最小值
  const rightYAxisMin = minSpeed < 0 ? minSpeed : 0;
  const rightYAxisMax = 1000; // 保持最大值不变
  const rightYAxisInterval = 250; // 保持间隔不变

  const series = seriesNames.map((name, index) => ({
    name: name,
    type: 'line',
    data: data.map(item => Math.round(item.values[index] || 0)),
    smooth: true,
    lineStyle: {
      width: 2,
      color: colors[index]
    },
    itemStyle: {
      color: colors[index]
    },
    symbol: 'circle',
    symbolSize: 4,
    // 为速度设定mpm和速度实际mpm使用右侧Y轴，实际转矩使用左侧Y轴
    yAxisIndex: index === 1 ? 0 : 1
  }));

  // Fixed Y-axis range from 0 to 12000, divided into 5 equal parts

  const option = {
    title: {
      text: ``,
      textStyle: {
        color: '#fff',
        fontSize: 14
      }
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(0,0,0,0.9)',
      borderColor: '#42b4ff',
      borderWidth: 1,
      textStyle: {
        color: '#fff',
        fontSize: 12
      },
      formatter: function (params: any) {
        let result = params[0].axisValue + '<br/>';
        params.forEach((param: any) => {
          // 所有值都显示为整数
          let value;
          if (typeof param.value === 'number') {
            value = Math.round(param.value).toString();
          } else {
            value = param.value;
          }
          result += param.marker + param.seriesName + ': ' + value + '<br/>';
        });
        return result;
      },
      position: function (point: number[], params: any, dom: any, rect: any, size: any) {
        // 确保tooltip始终显示在可视区域内
        const chartWidth = size.viewSize[0];
        const chartHeight = size.viewSize[1];
        const tooltipWidth = size.contentSize[0];
        const tooltipHeight = size.contentSize[1];

        let x = point[0];
        let y = point[1];

        // 水平位置调整
        if (x + tooltipWidth > chartWidth) {
          x = x - tooltipWidth;
        }
        if (x < 0) {
          x = 10;
        }

        // 垂直位置调整
        if (y + tooltipHeight > chartHeight) {
          y = y - tooltipHeight;
        }
        if (y < 0) {
          y = 10;
        }

        return [x, y];
      },
      confine: true,
      appendToBody: true,
      z: 9999
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: times,
      axisLabel: {
        color: '#fff'
      },
      axisLine: {
        lineStyle: {
          color: '#42b4ff'
        }
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '转矩',
        nameTextStyle: {
          color: '#fff',
          fontSize: 12
        },
        min: 0,
        max: 12000,
        interval: 3000,
        axisLabel: {
          color: '#fff'
        },
        axisLine: {
          lineStyle: {
            color: '#42b4ff'
          }
        },
        splitLine: {
          lineStyle: {
            color: 'rgba(66,180,255,0.3)'
          }
        },
        position: 'left'
      },
      {
        type: 'value',
        name: '速度',
        nameTextStyle: {
          color: '#fff',
          fontSize: 12
        },
        min: rightYAxisMin,
        max: rightYAxisMax,
        interval: rightYAxisInterval,
        axisLabel: {
          color: '#fff'
        },
        axisLine: {
          lineStyle: {
            color: '#5dd1fa'
          }
        },
        splitLine: {
          show: false
        },
        position: 'right'
      }
    ],
    series: series
  };

  chartInstance.setOption(option);
};

// 初始化折线图
const initLineCharts = () => {
  // 初始化图表1
  if (lineChart1Ref.value && !lineChart1Instance) {
    lineChart1Instance = echarts.init(lineChart1Ref.value);
    const option1 = {
      title: {
        text: '',
        textStyle: {
          color: '#fff',
          fontSize: 14
        }
      },
      tooltip: {
        trigger: 'axis',
        backgroundColor: 'rgba(0,0,0,0.8)',
        borderColor: '#42b4ff',
        textStyle: {
          color: '#fff'
        },
        formatter: function (params: any) {
          let result = params[0].axisValue + '<br/>';
          params.forEach((param: any) => {
            // 所有值都显示为整数
            let value;
            if (typeof param.value === 'number') {
              value = Math.round(param.value).toString();
            } else {
              value = param.value;
            }
            result += param.marker + param.seriesName + ': ' + value + '<br/>';
          });
          return result;
        }
      },
      legend: {
        textStyle: {
          color: '#fff'
        },
        top: 30
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: [],
        axisLabel: {
          color: '#fff'
        },
        axisLine: {
          lineStyle: {
            color: '#42b4ff'
          }
        }
      },
      yAxis: [
        {
          type: 'value',
          name: '转矩',
          nameTextStyle: {
            color: '#fff',
            fontSize: 12
          },
          min: 0,
          max: 12000,
          interval: 3000,
          axisLabel: {
            color: '#fff'
          },
          axisLine: {
            lineStyle: {
              color: '#42b4ff'
            }
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(66,180,255,0.3)'
            }
          },
          position: 'left'
        },
        {
          type: 'value',
          name: '速度',
          nameTextStyle: {
            color: '#fff',
            fontSize: 12
          },
          min: 0,
          max: 1000,
          interval: 250,
          axisLabel: {
            color: '#fff'
          },
          axisLine: {
            lineStyle: {
              color: '#5dd1fa'
            }
          },
          splitLine: {
            show: false
          },
          position: 'right'
        }
      ],
      series: []
    };
    lineChart1Instance.setOption(option1);
  }

  // 初始化图表2
  if (lineChart2Ref.value && !lineChart2Instance) {
    lineChart2Instance = echarts.init(lineChart2Ref.value);
    const option2 = {
      title: {
        text: '',
        textStyle: {
          color: '#fff',
          fontSize: 14
        }
      },
      tooltip: {
        trigger: 'axis',
        backgroundColor: 'rgba(0,0,0,0.8)',
        borderColor: '#42b4ff',
        textStyle: {
          color: '#fff'
        },
        formatter: function (params: any) {
          let result = params[0].axisValue + '<br/>';
          params.forEach((param: any) => {
            // 所有值都显示为整数
            let value;
            if (typeof param.value === 'number') {
              value = Math.round(param.value).toString();
            } else {
              value = param.value;
            }
            result += param.marker + param.seriesName + ': ' + value + '<br/>';
          });
          return result;
        }
      },
      legend: {
        textStyle: {
          color: '#fff'
        },
        top: 30
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: [],
        axisLabel: {
          color: '#fff'
        },
        axisLine: {
          lineStyle: {
            color: '#42b4ff'
          }
        }
      },
      yAxis: [
        {
          type: 'value',
          name: '转矩',
          nameTextStyle: {
            color: '#fff',
            fontSize: 12
          },
          min: 0,
          max: 12000,
          interval: 3000,
          axisLabel: {
            color: '#fff'
          },
          axisLine: {
            lineStyle: {
              color: '#42b4ff'
            }
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(66,180,255,0.3)'
            }
          },
          position: 'left'
        },
        {
          type: 'value',
          name: '速度',
          nameTextStyle: {
            color: '#fff',
            fontSize: 12
          },
          min: 0,
          max: 1000,
          interval: 250,
          axisLabel: {
            color: '#fff'
          },
          axisLine: {
            lineStyle: {
              color: '#5dd1fa'
            }
          },
          splitLine: {
            show: false
          },
          position: 'right'
        }
      ],
      series: []
    };
    lineChart2Instance.setOption(option2);
  }

  // 初始化图表3
  if (lineChart3Ref.value && !lineChart3Instance) {
    lineChart3Instance = echarts.init(lineChart3Ref.value);
    const option3 = {
      title: {
        text: '',
        textStyle: {
          color: '#fff',
          fontSize: 14
        }
      },
      tooltip: {
        trigger: 'axis',
        backgroundColor: 'rgba(0,0,0,0.8)',
        borderColor: '#42b4ff',
        textStyle: {
          color: '#fff'
        },
        formatter: function (params: any) {
          let result = params[0].axisValue + '<br/>';
          params.forEach((param: any) => {
            // 所有值都显示为整数
            let value;
            if (typeof param.value === 'number') {
              value = Math.round(param.value).toString();
            } else {
              value = param.value;
            }
            result += param.marker + param.seriesName + ': ' + value + '<br/>';
          });
          return result;
        }
      },
      legend: {
        textStyle: {
          color: '#fff'
        },
        top: 30
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: [],
        axisLabel: {
          color: '#fff'
        },
        axisLine: {
          lineStyle: {
            color: '#42b4ff'
          }
        }
      },
      yAxis: [
        {
          type: 'value',
          name: '转矩',
          nameTextStyle: {
            color: '#fff',
            fontSize: 12
          },
          min: 0,
          max: 12000,
          interval: 3000,
          axisLabel: {
            color: '#fff'
          },
          axisLine: {
            lineStyle: {
              color: '#42b4ff'
            }
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(66,180,255,0.3)'
            }
          },
          position: 'left'
        },
        {
          type: 'value',
          name: '速度',
          nameTextStyle: {
            color: '#fff',
            fontSize: 12
          },
          min: 0,
          max: 1000,
          interval: 250,
          axisLabel: {
            color: '#fff'
          },
          axisLine: {
            lineStyle: {
              color: '#5dd1fa'
            }
          },
          splitLine: {
            show: false
          },
          position: 'right'
        }
      ],
      series: []
    };
    lineChart3Instance.setOption(option3);
  }
};
</script>

<style scoped lang="less">
.cgl-container {
  position: relative;
  background: url("../../assets/images/body-bg.jpg") no-repeat center center;
  background-size: cover;
  height: 100vh;
  width: 100%;
  overflow: hidden;
  color: #fff;
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: "Microsoft YaHei", Arial, sans-serif;
  display: flex;
  flex-direction: column;
}

/* 头部样式 */
.header {
  flex: 0 0 60px;
  background-image: url("../../assets/images/head-bg.png");
  background-size: 100% 100%;
  background-repeat: no-repeat;
  display: flex;
  align-items: flex-start;
  justify-content: center;
  position: relative;
  z-index: 10;
  padding-top: 3px;
  margin-bottom: -15px;
}

.titleMain {
  font-size: 20px;
  color: #ffffff;
  text-align: center;
  text-shadow: 0 0 10px #42b4ff, 0 0 20px #0a2466;
  letter-spacing: 2px;
}

/* Top Charts Panel */
.top-charts-panel {
  display: flex;
  margin: 0 5px;
  height: 190px;
  flex-shrink: 0;
  position: relative;
  z-index: 20;
}

.chart-card {
  /* background-image: url('../../assets/img/itme_bg.png'); */
  /* 移除背景图 */
  /* background-size: cover; */
  /* background-position: center; */
  background-color: rgba(28, 58, 99, 0.7);
  /* 设置半透明背景色 */
  border: 1px solid rgba(90, 130, 190, 0.4);
  border-radius: 0;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
  margin-right: 5px;
  box-shadow: 0 0 15px rgba(11, 93, 209, 0.2);
}

.chart-card:last-child {
  margin-right: 0;
}

.status-chart {
  flex: 1.5;
}

.line-chart {
  flex: 1;
}

.chart-header {
  background-image: url("../../assets/img/sub_title_bg.png");
  background-size: 100% 100%;
  background-repeat: no-repeat;
  position: relative;
  height: 30px;
  width: 100%;
  border-bottom: 1px solid rgba(58, 90, 138, 0.6);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-bar {
  display: flex;
  align-items: center;
  padding-left: 10px;
}

.blue-bar {
  display: inline-block;
  width: 3px;
  height: 16px;
  background-color: #42b4ff;
  margin-right: 8px;
  box-shadow: 0 0 8px #42b4ff;
}

.title-text {
  font-size: 13px;
  font-weight: bold;
  color: #a2dfff;
  text-shadow: 0 0 5px rgba(66, 180, 255, 0.5);
}

.chart-buttons {
  padding-right: 10px;
}

:deep(.el-radio-button__inner) {
  background-color: transparent;
  border: none;
  color: #a0a3a8;
  padding: 4px 8px;
  font-size: 12px;
  height: 24px;
  line-height: 16px;
}

:deep(.el-radio-button__orig-radio:checked + .el-radio-button__inner) {
  color: #42b4ff;
  border-bottom: 2px solid #42b4ff;
  background-color: transparent;
  box-shadow: none;
  text-shadow: 0 0 5px #42b4ff;
}

:deep(.el-radio-button:first-child .el-radio-button__inner),
:deep(.el-radio-button:last-child .el-radio-button__inner) {
  border-radius: 0px;
}

.chart-controls {
  padding-right: 10px;
}

/* 深度选择器修改 el-select 内部元素的样式 */
:deep(.torque-select .el-select__wrapper) {
  background-color: rgba(41, 121, 255, 0.2) !important;
  border: 1px solid #42b4ff !important;
  box-shadow: 0 0 8px rgba(41, 121, 255, 0.5) !important;
  height: 22px !important;
  width: 110px;
}

:deep(.torque-select .el-input__inner) {
  height: 20px !important;
  line-height: 20px !important;
  font-size: 11px !important;
  color: #fff !important;
  padding: 0 10px;
}

:deep(.torque-select .el-select__caret) {
  font-size: 11px !important;
  color: #42b4ff;
}

:deep(.torque-select .el-select__placeholder) {
  font-size: 11px !important;
  color: #a0a3a8;
}

.chart-content {
  flex-grow: 1;
  width: 100%;
  height: calc(100% - 30px);
  position: relative;
  z-index: 100;
}

/* Process Stats Panel */
.process-stats-panel {
  flex-grow: 1;
  margin: 10px 5px 5px;
  position: relative;
  /* background-image: url("../../assets/svgs/CAL1630.svg"); */
  background-size: 100% 100%;
  background-position: center;
  background-repeat: no-repeat;
  min-height: 250px;
  width: 100%;

  .roll-pos-image-block {
    position: absolute;
    top: 0;
    height: 100%;
  }

  .roll-pos-image-block:nth-child(1) {
    left: 0;
    width: 35%;
  }

  .roll-pos-image-block:nth-child(2) {
    left: 35%;
    width: 38%;
  }

  .roll-pos-image-block:nth-child(3) {
    right: 0;
    width: 27%;
  }

  .svg {
    width: 100%;
    height: 100%;

    svg {
      width: 100%;
      height: 100%;
    }
  }
}

.process-diagram {
  position: relative;
  width: 100%;
  height: 100%;
}

.stats-overlay-container {
  position: absolute;
  bottom: 330px;
  left: 0;
  width: 100%;
  display: flex;
  justify-content: space-around;
  padding: 0 4%;
  z-index: 5;
}

.stat-card {
  position: relative;
  width: 100px;
  height: 40px;
  border-radius: 8px;
  //overflow: hidden;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  backdrop-filter: blur(3px);
}

.stat1 {
  position: relative;
  left: -5%;
}

.stat2 {
  position: relative;
  left: 17%;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(66, 180, 255, 0.4);
}

.stat-card::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url("../../assets/img/zl-pic52.png") center bottom no-repeat;
  background-size: contain;
  z-index: 0;
  border-radius: 8px;
  filter: brightness(1.2);
}

.stat-card-content {
  position: relative;
  z-index: 1;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 10px;
  clip-path: polygon(0 0, 100% 0, 100% 88%, 88% 100%, 0 100%);
}

.stat-title {
  font-size: 13px;
  color: #a2cfff;
  margin-bottom: 8px;
  text-shadow: 0 0 5px rgba(100, 180, 255, 0.7);
  font-weight: 500;
}

.stat-value {
  font-size: 13px;
  font-weight: bold;
  color: #fff;
  text-shadow: 0 0 8px rgba(100, 180, 255, 0.8);
  line-height: 1.2;
}

.stat-value .unit {
  font-size: 13px;
  font-weight: normal;
  opacity: 0.8;
  margin-left: 3px;
}

.stat-icon {
  position: absolute;
  top: 12px;
  right: 12px;
  width: 28px;
  height: 28px;
  background: rgba(66, 180, 255, 0.15);
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 0 8px rgba(66, 180, 255, 0.4);
  animation: rotate-icon 12s infinite linear;
}

@keyframes rotate-icon {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.stat-icon i {
  font-size: 15px;
  color: #6dc7ff;
}

.stat-card-glow {
  position: absolute;
  bottom: -5px;
  left: 50%;
  transform: translateX(-50%);
  width: 75%;
  height: 8px;
  background: rgba(66, 180, 255, 0.7);
  border-radius: 50%;
  filter: blur(7px);
  animation: glow 2.5s infinite alternate;
  z-index: 0;
}

@keyframes glow {
  0% {
    opacity: 0.4;
    width: 65%;
  }

  100% {
    opacity: 0.8;
    width: 75%;
  }
}

.tension-info {
  position: absolute;
  top: 3px;
  right: 10px;
  font-size: 12px;
  color: #c0c4cc;
}

.tension-info strong {
  color: #fff;
  font-weight: bold;
  text-shadow: 0 0 5px rgba(41, 121, 255, 0.7);
}

/* Warning Banner */
.warning-banner {
  width: 400px;
  background-color: rgba(255, 77, 79, 0.8);
  color: #fff;
  padding: 4px 15px;
  margin: 0 5px 5px;
  font-size: 13px;
  text-align: center;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #ea0f0f;
  box-shadow: 0 0 10px rgba(255, 77, 79, 0.5);
  animation: flash 2s infinite;
}

.warning-banner i {
  margin-right: 8px;
  color: #fff;
}

/* Bottom Panel Styles */
.bottom-panel {
  padding: 5px;
  flex-shrink: 0;
  height: 190px;
}

/* Wrapper for the two table cards */
.tables-wrapper {
  display: flex;
  height: 100%;
  gap: 5px;
}

/* General Table Card Style */
.table-card {
  display: flex;
  flex-direction: column;
  background-color: rgba(28, 58, 99, 0.7);
  border: 1px solid rgba(90, 130, 190, 0.4);
  box-shadow: 0 0 15px rgba(11, 93, 209, 0.2);
  overflow: hidden;
}

/* Style for left table card */
.left-table-card {
  flex-shrink: 0;
  width: 100%;
}

/* Style for right table card */
.right-table-card {
  flex-grow: 1;
}

/* Card Header Style (similar to chart headers) */
.card-header {
  background-image: url("../../assets/img/sub_title_bg.png");
  background-size: 100% 100%;
  background-repeat: no-repeat;
  padding: 6px 15px;
  font-weight: bold;
  flex-shrink: 0;
  border-bottom: 1px solid rgba(58, 90, 138, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  height: 3.5vh;
  line-height: 3.5vh;
}

/* Style for the title text span */
.card-header span {
  background-image: -webkit-linear-gradient(left, #0072ff, #00eaff, #01aaff);
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
  font-weight: bolder;
  font-size: 1.7vh;
}

/* Copied Icon Styles from NewCoilCard */
.title-icon-left {
  margin-right: 1vw;
  transform: rotateY(180deg);
  width: 2vw;
  height: 3vh;
  background-image: url(/src/assets/images/title-icon-right.png);
  background-size: 100% 100%;
}

.title-icon-right {
  margin-left: 1vw;
  width: 2vw;
  height: 3vh;
  background-image: url(/src/assets/images/title-icon-right.png);
  background-size: 100% 100%;
}

/* Ensure tables fill the card content area */
.left-table,
.right-table {
  flex-grow: 1;
  width: 100% !important;
  height: 100% !important;
  background-color: transparent !important;
  border: none !important;
}

/* Deep Table Styles from XGRPH.vue */
:deep(.el-table) {
  background-color: transparent !important;
  border: none !important;
}

:deep(.el-table tr:nth-child(odd)) {
  background-color: #0f2142 !important;
}

:deep(.el-table tr:nth-child(even)) {
  background-color: #142a52 !important;
}

:deep(.el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell) {
  background-color: rgba(66, 180, 255, 0.1) !important;
}

:deep(.el-table td.el-table__cell),
:deep(.el-table th.el-table__cell) {
  background-color: transparent !important;
  border-color: #06279d !important;
  color: #c0c4cc;
}

:deep(.el-table th.el-table__cell) {
  color: #b8e8ff;
  background-color: #183272 !important;
  border-bottom: 1px solid #06279d !important;
}

:deep(.el-table--border .el-table__inner-wrapper::after),
:deep(.el-table--border::after),
:deep(.el-table--border::before),
:deep(.el-table__border-left-patch),
:deep(.el-table--border .el-table__inner-wrapper::before) {
  background-color: #06279d !important;
}

:deep(.el-table td.el-table__cell),
:deep(.el-table th.el-table__cell.is-leaf) {
  border-bottom: 1px solid #06279d !important;
}

:deep(.el-table--border td.el-table__cell),
:deep(.el-table--border th.el-table__cell) {
  border-right: 1px solid #06279d !important;
}

:deep(.el-table__body-wrapper) {
  scrollbar-width: thin;
  scrollbar-color: #3a5a8a #142a52;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar) {
  width: 6px;
  height: 6px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-track) {
  background: #142a52;
  border-radius: 3px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
  background-color: #3a5a8a;
  border-radius: 3px;
}

@keyframes flash {

  0%,
  100% {
    opacity: 1;
  }

  50% {
    opacity: 0.7;
  }
}

@keyframes glow {

  0%,
  100% {
    filter: brightness(1);
  }

  50% {
    filter: brightness(1.3);
  }
}

/* Styles for newly added ZLGDH data display */
.zlgdh-added-data-layer {
  /* This layer itself might not need specific positioning if its children are all absolute */
  /* position: absolute; */
  /* Potentially remove if .process-stats-panel is the main relative parent */
  /* top: 0; left: 0; right: 0; bottom: 0; */
  /* Make it cover the parent if needed */
  /* z-index: 15; */
  /* display: flex; */
  /* Remove flex if children are absolute */
  /* flex-direction: column; */
  /* gap: 5px; */
}

/* Remove .zlgdh-gauge-row and .zlgdh-live-data-row styling as they are removed from HTML */

.gauge-wrapper {
  position: absolute;
  /* Key for precise placement */
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 5px;
  z-index: 20;
  /* Ensure gauges are above the data layer background if any */
}

.gauge-title {
  font-size: 11px;
  color: #a2dfff;
  margin-bottom: 2px;
  /* Reduced margin */
}

.gauge-container {
  width: 90px;
  /* Slightly smaller default */
  height: 90px;
  /* Slightly smaller default */
}

/* START: Precise positioning examples - YOU NEED TO ADJUST THESE VALUES */
.zlgdh-gauge-ent {
  top: 10%;
  /* Example value */
  left: 17%;
  /* Example value */
}

.zlgdh-gauge-process {
  top: 10%;
  /* Example value */
  left: 26%;
  /* Example value */
  transform: translateX(-50%);
  /* Center if using left: 50% */
}

.zlgdh-gauge-exit {
  top: 18%;
  /* Example value */
  right: 5%;
  /* Example value */
}

/* Styling for individual data boxes, now absolutely positioned */
.semitransp_box {
  position: absolute;
  /* Key for precise placement */
  background: rgba(6, 62, 144, 0.75);
  color: #fff;
  padding: 3px 6px;
  /* Slightly smaller padding */
  border-radius: 3px;
  font-size: 10px;
  /* Smaller font */
  text-align: center;
  border: 1px solid rgba(66, 180, 255, 0.35);
  z-index: 20;
  min-width: 100px;
  /* Ensure some minimum width */
}

.semitransp_box p {
  margin: 0 2px;
  display: block;
  /* Change to block for title and value on separate lines */
  line-height: 1.3;
  /* Adjust line height */
}

.semitransp_box p:first-child {
  font-weight: normal;
  opacity: 0.8;
  font-size: 9px;
  /* Smaller title font */
}

.semitransp_box p:last-child {
  font-weight: bold;
  font-size: 11px;
  /* Value font size */
}

/* Example positioning for data boxes - YOU NEED TO ADJUST THESE */
.zlgdh_inlet_looper {
  top: 15%;
  left: 10%;
}

.zlgdh_middle_looper {
  top: 19%;
  left: 35%;
  transform: translateX(-50%);
}

.zlgdh_export_looper {
  top: 19%;
  right: 21%;
}

.zlgdh_cpc_width {
  top: 77%;
  left: 43%;
}

.zlgdh_inlet_looper_time {
  top: 26%;
  left: 10%;
}

.zlgdh_middle_looper_time {
  top: 30%;
  left: 35%;
  transform: translateX(-50%);
}

.zlgdh_export_looper_time {
  top: 30%;
  right: 21%;
}

.zlgdh_uncoiler_len_a {
  bottom: 42%;
  left: 1%;
}

.zlgdh_uncoiler_len_b {
  bottom: 5%;
  left: 1%;
}

.zlgdh_coiler_len_a {
  bottom: 34%;
  right: 1%;
}

.zlgdh_coiler_len_b {
  bottom: -1%;
  right: 4%;
}

/* END: Precise positioning examples */

.semitransp_box.is_alarm {
  background-color: #fe2400 !important;
}

/* Ensure .process-stats-panel can contain absolutely positioned children */
.process-stats-panel {
  position: relative;
  /* This is crucial for absolute positioning of children */
  /* You might need to adjust its height if children are positioned outside its flow */
}

.process-diagram {
  /* Ensure SVG background does not get a higher z-index by mistake if it also becomes positioned */
  position: relative;
  z-index: 1;
  /* Lower z-index than data overlays */
  /* height: 100%; */
  /* Or specific height to control its area */
}

/* You might need to adjust existing elements like stats-overlay-container if they overlap */
.stats-overlay-container {
  z-index: 25;
  /* Ensure it's above new data boxes if necessary */
}
</style>